<?php
class AdminAtion extends CAction
{
    public function run()
    {
        $module = $this->controller->get('module', $this->controller->taxModule);
        $type = $this->controller->get('type', $this->controller->voc);

        //Alow use alias beside id in type get.
        if (!is_numeric($type)) {
            $taxo = Vocabulary::model()->findByAttributes(array('alias' => $type));
            if ($taxo)
                $type = $taxo->id;
            else $type = 0;
        }

        $this->controller->render('admin', array(
            'module' => $module,
            'type' => $type,
            'modules' => $this->getModules($module),
            'types' => $this->getVocabularies($type, $module),
            'models' => $this->getTerms($type),
        ));
    }

    /**
     * get all vocabularies by module
     * valid current vocabulary
     *
     * @param int $type vocabulary
     * @param string $module module ID
     *
     * @return array
     */
    protected function getVocabularies($type, $module)
    {
        $criteria = new CDbCriteria;
        $criteria->compare('module', $module);
        $criteria->order = 'name';
        $types = Vocabulary::model()->findAll($criteria);
        if (count($types))
            $types = CHtml::listData($types, 'id', 'name');

        if ($type && !array_key_exists($type, $types))
            throw new CHttpException(500, 'Invalid Type');

        return $types;
    }

    /**
     * get root term by vocabulary id
     *
     * @param int $type vocabulary IDs
     *
     * @return array Term
     */
    protected function getTerms($type)
    {
        $criteria = new CDbCriteria;
        $criteria->compare('v_id', $type);
        return Term::model()->findAll($criteria);
    }

    /**
     * get all modules of system
     * valid current module is exist
     *
     * @param string $module
     *
     * @return array
     */
    protected function getModules($module)
    {
        $modules = Module::model()->findAll();
        if (count($modules))
            $modules = CHtml::listData($modules, 'name', 'friendly_name');

        if (empty($module) === false && $module != 'system' && !array_key_exists($module, $modules))
            throw new CHttpException(500, 'Invalid module');

        return $modules;
    }
}